package cn.bdqn.service.impl;

import cn.bdqn.dto.Dto;

import cn.bdqn.mapper.ItripUserMapper;
import cn.bdqn.pojo.ItripUser;
import cn.bdqn.service.UserService;
import cn.bdqn.util.MD5Utils;
import cn.bdqn.vo.ItripUserRegInfo;
import com.cloopen.rest.sdk.CCPRestSmsSDK;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2018/8/20.
 */
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private ItripUserMapper itripUserMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private SimpleMailMessage mailMessage;
    @Resource
    private JavaMailSender mailSender;
    String code = "";

    @Override
    public Dto regdit(ItripUserRegInfo userInfo) {
        ItripUser user = new ItripUser();
        user.setUserName(userInfo.getUserName());
        user.setUserCode(userInfo.getUserCode());
        user.setUserPassword(MD5Utils.getMD5(userInfo.getUserPassword(),6));
        user.setUserType(0);
        user.setCreationDate(new Date());
        user.setActivated(0);
        Dto dto = new Dto();
        if (user.getUserCode().contains("@")) {
            //进入邮箱验证
            if (!validEmail(user.getUserCode())) {
                dto.setCode("10001");
                dto.setMsg("邮箱格式不正确，请重新注册！");
                dto.setSuccess("false");
                return dto;
            }
            //激活邮箱
            activeEmail(user.getUserCode());
        } else {
            //进入手机号验证
            if (!validPhone(user.getUserCode())) {
                dto.setCode("10002");
                dto.setMsg("手机格式不正确，请重新注册！");
                dto.setSuccess("false");
                return dto;
            } else {
                //激活手机
                activePhone(user.getUserCode());
            }
        }




        //添加用户注册信息到数据库
        if (itripUserMapper.insert(user) <= 0) {
            dto.setCode("10006");
            dto.setMsg("注册失败");
            dto.setSuccess("false");
            return dto;
        }
        dto.setCode("0");
        dto.setMsg("注册成功");
        dto.setData(user);
        return dto;
    }


    @Override
    public Dto active(String userCode, String activeCode) {
        Dto dto = new Dto();
        String code = stringRedisTemplate.opsForValue().get("active:" + userCode);
        if (code != null && activeCode.equalsIgnoreCase(code)) {
            ItripUser user = itripUserMapper.selectUserByUserCode(userCode);
            user.setActivated(1);
            user.setCreatedBy(user.getId());
            user.setFlatID(user.getId());
            if (this.updateUserByUserCode(user)) {
                //激活成功后在redius中删除激活码并且设置用户激活码状态为1
                stringRedisTemplate.delete("active:" + userCode);
                dto.setCode("0");
                dto.setMsg("激活成功");
            }
        } else {
            dto.setCode("10001");
            dto.setMsg("验证码不正确或已失效");
            dto.setSuccess("false");
        }
        return dto;
    }

    @Override
    public ItripUser getUserByUserCode(String userCode) {
        return itripUserMapper.selectUserByUserCode(userCode);
    }

    @Override
    public Boolean updateUserByUserCode(ItripUser user) {
        return itripUserMapper.updateUserByUserCode(user) > 0;
    }

    /**
     * 合法E-mail地址：
     * 1. 必须包含一个并且只有一个符号“@”
     * 2. 第一个字符不得是“@”或者“.”
     * 3. 不允许出现“@.”或者.@
     * 4. 结尾不得是字符“@”或者“.”
     * 5. 允许“@”前的字符中出现“＋”
     * 6. 不允许“＋”在最前面，或者“＋@”
     */
    private boolean validEmail(String email) {
        String regex = "^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$";
        return Pattern.compile(regex).matcher(email).find();
    }

    /**
     * 验证是否合法的手机号
     *
     * @param phone
     * @return
     */
    private boolean validPhone(String phone) {
        String regex = "^1[3578]{1}\\d{9}$";
        return Pattern.compile(regex).matcher(phone).find();
    }

    //激活邮箱操作
    @Override
    public Dto activeEmail(String userCode) {
        Dto dto = new Dto();
//        if(itripUserMapper.selectUserByUserCode(userCode)==null){
//            dto.setMsg("用户账号不存在");
//            dto.setCode("10086");
//            return dto;
//        }

            //进入邮箱注册
            //邮箱注册
            //接收到用户注册信息
            //调用dao进行持久化操作 userMapper.insertUser
            //密码加密 md5加密不可逆 撞库 结果不是有效 对象。方法（参数）
            //判断邮箱还是手机号
            //生成验证码 UUID生成对象.方法
            code = UUID.randomUUID().toString();
            //保存redis
            //redis操作 StringRedisTemplate 有效期
            stringRedisTemplate.opsForValue().set("active:" + userCode, code, 60, TimeUnit.SECONDS);
            //发送邮件到用户邮箱
            mailMessage.setTo(userCode);
            mailMessage.setText("你的激活码是：" + code);
            mailSender.send(mailMessage);
//        redisTemplate.opsForHash().put("user", ItripUser.class, record);
//        ItripUser user = (ItripUser) redisTemplate.opsForHash().get("user", ItripUser.class);
        return dto;
    }

    //登陆
    @Override
    public Dto selectLogin(ItripUser itripUser) {
        Dto dto = new Dto();
        if (!this.selectItripUserActive(itripUser.getUserCode())) {
            dto.setCode("10002");
            dto.setMsg("用户未激活");
            dto.setSuccess("false");
            return dto;
        }
        ItripUser itripUser1 = itripUserMapper.selectByUserCodeAndUserPassword(itripUser);
        if (itripUser1 != null) {
            dto.setCode("0");
            dto.setMsg("登陆成功");
            dto.setData(itripUser1);
            return dto;
        } else {
            dto.setCode("10001");
            dto.setMsg("登陆失败");
            dto.setSuccess("false");
            return dto;
        }
    }

    //判断用户是否激活
    @Override
    public boolean selectItripUserActive(String userCode) {
        ItripUser itripUser = itripUserMapper.selectUserByUserCode(userCode);
        int actived = itripUser.getActivated();
        if (actived == 1) {
            return true;
        }
        return false;
    }

    //判断用户是否注册
    @Override
    public Dto selectItripUserRepeat(String userCode) {
        Dto dto=new Dto();
        if(userCode==null || userCode==""){
            dto.setCode("10002");
            dto.setMsg("用户名不能为空");
            dto.setSuccess("false");
            return dto;
        }
        ItripUser itripUser=itripUserMapper.selectUserByUserCode(userCode);
        if(itripUser!=null){
            dto.setCode("10001");
            dto.setMsg("用户名已经被注册");
            dto.setSuccess("false");
        }else{
            dto.setCode("0");
            dto.setMsg("用户名可以使用");
        }
        return dto;
    }





    @Override
    public ItripUser findByUsername(String username) throws Exception {

        Map<String,Object> param=new HashMap<>();
        param.put("useCode",username);
        List<ItripUser> itripUserList = itripUserMapper.getItripUserListByMap(param);
        if (itripUserList.size()>0){
            return itripUserList.get(0);
        }else {
            return null;
        }
    }

    @Override
    public void itripCreateUser(ItripUser user) throws Exception {
                itripUserMapper.insert(user);
    }





    //激活手机号操作
    @Override
    public Dto activePhone(String userCode) {
        Dto dto = new Dto();
//        if(itripUserMapper.selectUserByUserCode(userCode)==null){
//            dto.setMsg("用户账号不存在");
//            dto.setCode("10086");
//            return dto;
//        }

        try {
            //进入手机注册
            HashMap<String, Object> result = null;
            CCPRestSmsSDK restAPI = new CCPRestSmsSDK();
            restAPI.init("app.cloopen.com", "8883");
            // 初始化服务器地址和端口，生产环境配置成app.cloopen.com，端口是8883.
            restAPI.setAccount("8a216da86521b65701652c0a621204b2", "238f4ce60cbe4058b4baca0ca2e12255");
            // 初始化主账号名称和主账号令牌，登陆云通讯网站后，可在控制首页中看到开发者主账号ACCOUNT SID和主账号令牌AUTH TOKEN。
            restAPI.setAppId("8a216da86521b65701652c0a626304b8");
            // 请使用管理控制台中已创建应用的APPID。

            //生成验证码 UUID生成对象.方法
            Random random = new Random();
            code = code + random.nextInt(9) + random.nextInt(9) + random.nextInt(9) + random.nextInt(9);
            //保存redis
            //redis操作 StringRedisTemplate 有效期
            stringRedisTemplate.opsForValue().set("active:" + userCode, code, 60, TimeUnit.SECONDS);
            result = restAPI.sendTemplateSMS(userCode, "1", new String[]{code});
            System.out.println("SDKTestGetSubAccounts result=" + result);
            //            if("000000".equals(result.get("statusCode"))){
//                //正常返回输出data包体信息（map）
//                HashMap<String,Object> data = (HashMap<String, Object>) result.get("data");
//                Set<String> keySet = data.keySet();
//                for(String key:keySet){
//                    Object object = data.get(key);
//                    System.out.println(key +" = "+object);
//                }
//            }else{
//                //异常返回输出错误码和错误信息
//                System.out.println("错误码=" + result.get("statusCode") +" 错误信息= "+result.get("statusMsg"));
//            }
            dto.setCode("0000");
            dto.setMsg("已重新发送短信");
        } catch (Exception e) {
            e.printStackTrace();
            dto.setCode("10086");
            dto.setMsg("重新发送短信失败");
            dto.setSuccess("false");
        }
        return dto;
    }



}
